package models.venue.curriculum;

import jodd.bean.BeanCopy;
import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import play.modules.paginate.JPAExtPaginator;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * 课程类型
 * Created by hanbin on 2017/4/5.
 */
@Entity
@Table(name="curriculum_types")
public class CurriculumType extends BaseModel {

    /**
     * 类型名称
     */
    @Column(name="type_name",length = 255)
    public String typeName;

    /**
     * 描述
     */
    @Column(name = "remark", length = 255)
    public String remark;

    /**
     * 所属店面
     */
    @JoinColumn(name="merchant_id")
    @ManyToOne
    public Merchant merchant;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 分页查询.
     */
    public static JPAExtPaginator<CurriculumType> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder("t.deleted=models.constants.DeletedStatus.UN_DELETED ")
                .append("/~ and t.typeName like {typeName} ~/")
                .append("/~ and t.merchant.id = {merchantId} ~/");

        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        JPAExtPaginator<CurriculumType> orderPage = new JPAExtPaginator<CurriculumType>("CurriculumType t", "t", CurriculumType.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        orderPage.setPageNumber(pageNumber);
        orderPage.setPageSize(pageSize);
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }

    /**
     * Update
     * @param id
     * @param newObject
     */
    public static void update(Long id, CurriculumType newObject) {
        CurriculumType curriculumType = CurriculumType.findById(id);
        BeanCopy.beans(newObject, curriculumType).ignoreNulls(true).copy();
        curriculumType.save();
    }

    /**
     * 根据商户查找课程类型
     * @return
     */
    public static List<CurriculumType> findAllCurriculumTypeByMerchant(long id){
        return find("deleted = ? and merchant.id = ? order by id", DeletedStatus.UN_DELETED, id).fetch();
    }

    /**
     * 判断课程类型是否被使用
     * @param typeId
     * @return
     */
    public static Boolean checkIsUsed(long typeId){
        return Curriculum.count("curriculumType.id = ? and deleted = ?" , typeId , DeletedStatus.UN_DELETED) > 0 ;
    }

}
